package com.sprite.framework.bone;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.Assert;

import com.sprite.utils.UtilMisc;

/**
 * spring 容器工具类
 */
public class SpringContextUtil implements ApplicationContextAware{
	private static ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		SpringContextUtil.applicationContext = applicationContext;
	}
	
	public static ApplicationContext getContext() {
		checkApplicationContext();
		return applicationContext;
	}

	public static <T> T getBean(String name) {
		checkApplicationContext();
		return UtilMisc.cast(applicationContext.getBean(name)) ;
	}

	public static <T> T getBean(Class<T> clazz) {
		checkApplicationContext();
		return (T) applicationContext.getBean(clazz);
	}

	private static void checkApplicationContext() {
		Assert.notNull(applicationContext,
				"applicaitonContext未注入,请在applicationContext.xml中定义SpringContextUtil");
	}


}
